/*
 * Copyright 2012 Gayan Perera
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
*/
package gap.maven.script.helpers;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.maven.plugin.logging.Log;

public abstract class AbstractLinker {
    
    protected final Log logger;

    public AbstractLinker(Log logger) {
        this.logger = logger;
    }
    
    /**
     * Creates a symbolic link (symlink) for given source path on the given link path. The path must be absolute path.
     * Creating symlink with relative paths will not be guaranteed.
     * 
     * @param sourcePath link source path (absolute).
     * @param linkPath link target path (absolute).
     * @throws IOException
     */
    public void createFileSymbolicLink(String sourcePath, String linkPath) throws IOException {
        // validate the arguments.
        File sourceFile = new File(sourcePath);
        if(!sourceFile.isFile()) {
            throw new IOException("sourceFile is not file or it doesn't exist.");
        }

        File targetFile = new File(linkPath);
        if(targetFile.exists()) {
            throw new IOException("targetPath already exist.");
        }
        
        performLinking(sourcePath, linkPath);
    }
    
    /**
     * Performs the actual linking operation using the given parameters.
     * @param sourcePath link source path (absolute).
     * @param linkPath link path (absolute).
     * @throws IOException
     */
    protected abstract void performLinking(String sourcePath, String linkPath) throws IOException;

    /**
     * Deletes the link only if it exist.
     * @param linkPath absolute path of the link.
     */
    public void deleteLink(String linkPath) {
        File link = new File(linkPath);
        if(link.isFile()) {
            link.delete();
            logger.debug("Link deleted : " + linkPath);
        }
    }
    
    
    /**
     * Prints the command output of the process.
     * @param stdout process standard output.
     * @param err process error output.
     */
    protected void printCommandOutput(InputStream stdout, InputStream err) {
        // put the output of the linker.
        try {
            if(logger.isDebugEnabled()) {
                StringBuilder builder = new StringBuilder();
                
                BufferedReader reader = new BufferedReader(new InputStreamReader(stdout));
                String line = reader.readLine();
                
                while(line != null) {
                    if(builder.length() == 0) {
                        builder.append("------------------- Linker Output -------------------\r\n");                    
                    }
                    builder.append(line).append("\r\n");
                    line = reader.readLine();
                }
 
                if(builder.length() > 0) {
                    logger.debug(builder.toString());
                }
            }
            
            if(logger.isErrorEnabled()) {
                StringBuilder builder = new StringBuilder();
                
                BufferedReader reader = new BufferedReader(new InputStreamReader(err));
                String line = reader.readLine();
                
                while(line != null) {
                    if(builder.length() == 0) {
                        builder.append("------------------- Linker Error -------------------\r\n");                    
                    }
                    builder.append(line).append("\r\n");
                    line = reader.readLine();
                }
 
                if(builder.length() > 0) {
                    logger.error(builder.toString());
                }
            }
            
        } catch (IOException ex) {
            logger.error("Error reading process streams.", ex);
        }
    }

}
